package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.security.auth.login.Configuration;
import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private QuestionService questionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private VisitorService visitorService;

    @DubboReference
    private UserLocationService userLocationService;

    // 查询今日佳人
    public ResponseEntity findTodayBest() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询今日佳人
        RecommendUser recommendUser = recommendUserService.findMaxScoreRecommendUser(userId);
        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findById(recommendUser.getUserId())); // 佳人的信息
        vo.setFateValue(recommendUser.getScore().longValue());// 缘分值
        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 查询推荐用户列表
    public ResponseEntity findRecommendation(Integer pageNum, Integer pageSize) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询推荐用户分页
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, pageNum, pageSize);
        // 3.封装vo
        // 3-1 声明vo集合
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3-2 取出recommendUser集合
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3-3 遍历
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfoService.findById(recommendUser.getUserId())); // 推荐用户信息
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值

                // 将vo设置到集合中
                voList.add(vo);
            }
        }
        // 4.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 查询推荐用户详情
    public ResponseEntity findPersonalInfo(Long recommendUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        RecommendUser recommendUser = null;
        // 2.判断前端请求入口是哪个：
        if (userId == recommendUserId) { // 我的动态
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId); // 这个值写自己用户id
            recommendUser.setScore(99D); // 这个值随便写

        } else { // 推荐用户详情
            recommendUser = recommendUserService.findRecommendUserByCondition(userId, recommendUserId);
        }

        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findById(recommendUser.getUserId()));
        vo.setFateValue(recommendUser.getScore().longValue());

        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 查询佳人的陌生人问题
    public ResponseEntity findStrangerQuestions(Long jiaRenId) {
        // 1.调用rpc查询对方陌生人问题
        Question question = questionService.findByUserId(jiaRenId);
        // 2.处理默认值
        if (question == null) {
            question = new Question();
        }
        // 3.返回对方陌生人问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    // 最近访客
    public ResponseEntity findVisitors() {
        // 1.声明voList
        List<VisitorVo> voList = new ArrayList<>();
        // 2.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 3.获取redis的上次登录时间
        String lassAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 4.如果有上次登录时间，就调用rpc查询
        if (StrUtil.isNotEmpty(lassAccessTime)) {
            List<Visitor> visitorList = visitorService.findVisitorByCondition(userId, Long.parseLong(lassAccessTime));
            // 5.遍历集合，封装vo
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    // 创建vo
                    VisitorVo vo = new VisitorVo();
                    vo.setUserInfo(userInfoService.findById(visitor.getVisitorUserId())); // 根据访客id查询信息
                    vo.setFateValue(visitor.getScore().longValue()); // 缘分值

                    // 添加到voList
                    voList.add(vo);
                }
            }
        }
        // 6.记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 7. 返回voList
        return ResponseEntity.ok(voList);
    }

    // 上报地理位置
    public void uploadLocation(Double longitude, Double latitude, String addrStr) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc上报地理位置
        userLocationService.uploadLocation(userId, longitude, latitude, addrStr);

    }

    // 搜附近
    public ResponseEntity searchNearUserVo(String gender, Double distance) {
        // 1.获取线程内的userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询附近人
        List<Long> nearUserIdList = userLocationService.searchNearUserId(userId, distance);
        // 3.条件排除
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {

                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 排除异性
                UserInfo nearUserInfo = userInfoService.findById(nearUserId);
                if (!StrUtil.equals(nearUserInfo.getGender(), gender)) {
                    continue;
                }

                // 封装vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(nearUserId);
                vo.setAvatar(nearUserInfo.getAvatar());
                vo.setNickname(nearUserInfo.getNickname());

                // 添加到集合中
                voList.add(vo);
            }
        }
        // 5.返回voList
        return ResponseEntity.ok(voList);
    }

    // 卡片查询
    public ResponseEntity searchCards() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.查询推荐用户
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, 1, 10);
        // 3.封装recommentUserVo
        // 3-1 声明VoList
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3-2 获取recommentUser集合
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3-3 遍历
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 查询推荐用户userInfo
                UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo); // 推荐用户信息
                vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值

                // 将vo添加list中
                voList.add(vo);

            }
        }
        // 4.返回voList
        return ResponseEntity.ok(voList);
    }
}
